/*
 Copyright (C) 2010 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.bizz.security.member;

import java.io.Serializable;
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 部门
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">Zhao Fangfang</a>
 * @since 0.2, 2010-10-4
 * @version $Id: BusinessUnit.java 7 2011-05-15 16:40:50Z zhaofang123@gmail.com $
 */
public class BusinessUnit extends MemberGroup {
	private static final long serialVersionUID = -1751170855052911017L;

	private User principal;
	
	private BusinessUnit parentBizUnit;
	private Set<BusinessUnit> childBizUnits = new HashSet<BusinessUnit>();
	
	/**
	 * @param identity
	 * @param name
	 * @param disabled
	 */
	public BusinessUnit(Serializable identity, String name, boolean disabled) {
		super(identity, name, disabled);
	}
	
	@Override
	public boolean addMember(Principal user) {
		if (!super.addMember(user))
			return false;
		((User) user).setOwningBizUnit(this);
		return true;
	}
	
	@Override
	public boolean removeMember(Principal user) {
		if (!super.removeMember(user))
			return false;
		((User) user).setOwningBizUnit(null);
		return true;
	}
	
	/**
	 * @return
	 */
	public User getPrincipal() {
		return principal;
	}
	
	/**
	 * @param principal
	 */
	public void setPrincipal(User principal) {
		this.principal = principal;
	}
	
	/**
	 * 获取父级部门
	 * 
	 * @return
	 */
	public BusinessUnit getParent() {
		return parentBizUnit;
	}
	
	/**
	 * 添加子部门
	 * 
	 * @param child
	 */
	public void addChild(BusinessUnit child) {
		if (childBizUnits.contains(child))
			return;
		childBizUnits.add(child);
		child.setParent(this);
	}
	
	/**
	 * 获取子部门列表
	 * 
	 * @return
	 */
	public Set<BusinessUnit> getChildren() {
		return Collections.<BusinessUnit>unmodifiableSet(childBizUnits);
	}
	
	/**
	 * 设置父级部门
	 * 
	 * @param parent
	 */
	protected void setParent(BusinessUnit parent) {
		this.parentBizUnit = parent;
	}
}
